package serve

import (
	"fmt"
	"gopkg.in/mgo.v2/bson"
	"svvenus/vpub/constants"
	"svvenus/znet/zpb"
	"time"
)

var (
	RecordState = false
	RecordChan  chan *Record
)

// RecordServe
// @Description: 日志
type RecordServe struct {
}

// NewRecordServe 创建
// @return *RecordServe
func NewRecordServe() *RecordServe {
	s := &RecordServe{}
	return s
}

// Start 开始
// @receiver sv
func (sv *RecordServe) Start() {
	RecordState = true
	RecordChan = make(chan *Record, 256)

	db := constants.MgoRecord.New()
	defer db.Close()

	for {
		select {
		case rec := <-RecordChan:
			{
				err := db.Create(rec)
				if err != nil {
					fmt.Println("RecordAdd Err", rec)
				}
			}
		}
	}
}

// Record
// @Description: 日志结构
type Record struct {
	Id        bson.ObjectId `json:"Id" bson:"_id,omitempty"`
	RecType   zpb.RecType   `bson:"RecType"`
	RecSource zpb.RecSource `bson:"RecSource"`
	RecTime   time.Time     `bson:"RecTime"`
	V1        string        `bson:"V1"`
	V2        string        `bson:"V2"`
	V3        string        `bson:"V3"`
	V4        string        `bson:"V4"`
	V5        string        `bson:"V5"`
	V6        string        `bson:"V6"`
	V7        string        `bson:"V7"`
	V8        string        `bson:"V8"`
	V9        string        `bson:"V9"`
}

func (obj *Record) CollectionName() string {
	return fmt.Sprintf("rec_%d", obj.RecType)
}
func (obj *Record) Id_() interface{} {
	return obj.Id
}

// NewRecord 新日志
// @param rt
// @param rs
// @param args
// @return *Record
func NewRecord(rt zpb.RecType, rs zpb.RecSource, args ...string) *Record {
	rec := &Record{}
	rec.RecType = rt
	rec.RecSource = rs
	rec.RecTime = time.Now()
	if len(args) > 0 {
		rec.V1 = args[0]
	}
	if len(args) > 1 {
		rec.V2 = args[1]
	}
	if len(args) > 2 {
		rec.V3 = args[2]
	}
	if len(args) > 3 {
		rec.V4 = args[3]
	}
	if len(args) > 4 {
		rec.V5 = args[4]
	}
	if len(args) > 5 {
		rec.V6 = args[5]
	}
	if len(args) > 6 {
		rec.V7 = args[6]
	}
	if len(args) > 7 {
		rec.V8 = args[7]
	}
	if len(args) > 8 {
		rec.V9 = args[8]
	}
	return rec
}

// RecordAdd 外部日志添加
// @param rt
// @param rs
// @param args
func RecordAdd(rt zpb.RecType, rs zpb.RecSource, args ...string) {
	if !RecordState {
		return
	}
	rec := NewRecord(rt, rs, args...)
	RecordChan <- rec
}
